import { useCallback, useEffect, useMemo, useState } from 'react'
import style from './VirtualListStyle.module.sass'

function VirtualList ({list}: {list: string[]}) {

  // #region 变量声明
  const [top, setTop] = useState(0)
  const itemHeight = 30
  const maxHeight = list.length * itemHeight
  const [visible, setVisible] = useState({start: 0, end: 0})
  const temp = 5
  const offset = useMemo(() =>{
    return visible.start * itemHeight
  }, [visible])
  const visibleLen = 10
  const item = useMemo(() => {
    return list.slice(visible.start, visible.end)
  }, [visible, list])
  // #endregion

  // #region 函数
  function scrollHandler (e: React.UIEvent<HTMLUListElement>) {
    const et = e.target as HTMLUListElement
    setTop(et.scrollTop)
  }
  const setVisibleFn = useCallback(() => {
    const start = Math.max(0, Math.floor(top / itemHeight) - temp)
    const end = Math.min(list.length, Math.ceil(top / itemHeight) + visibleLen + temp)
    return {start, end}
  }, [top, list])
  // #endregion

  // #region Hooks
  useEffect(() => {
    setVisible(setVisibleFn())
  }, [setVisibleFn])
  // #endregion

  return (
    <ul className={style.wrap} onScroll={scrollHandler}>
      <div className={style.visible} style={{top: `${offset}px`}}>
        {item.map((v, i) => <li key={i}>{v}</li>)}
      </div>
      {/* {list.map((v, i) => <li key={i}>{v}</li>)} */}
      <div className={style.max} style={{height: maxHeight}}></div>
    </ul>
  )
}

export default VirtualList
